package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.SensitiveDto;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmSensitiveService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive>
        implements WmSensitiveService {

    //redis缓存注入
    @Autowired
    private CacheService cacheService;

    private static final String sensitive_key = "sensitive_key";

    /**
     * 删除敏感词
     * @param id
     * @return
     */
    @Override
    public ResponseResult delSensitive(Integer id) {
        //判断前端传过来的参数是否为空
        if ( null == id){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id删除敏感词
        boolean result = removeById(id);
        if (result){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS );
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);

    }

    /**
     * 查询敏感词列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList( SensitiveDto dto) {

        //分页参数检查
        dto.checkParam();

        //分页查询
        IPage page = new Page(dto.getPage(),dto.getSize());
        //生成条件构造器
        LambdaQueryWrapper<WmSensitive> query = Wrappers.<WmSensitive>lambdaQuery();
        //判断模糊查询不为空
        if (StringUtils.isNotBlank(dto.getSensitives())){
            query.like(WmSensitive::getSensitives,dto.getSensitives());
        }
        query.orderByDesc(WmSensitive::getCreatedTime);
        //分页查询列表
        page = page(page,query);

         ResponseResult responseResult = new PageResponseResult();
         responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 保存敏感词
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveWmSensitive(WmSensitive dto) {
        if (StringUtils.isBlank(dto.getSensitives())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否已存在
        int  count = count(Wrappers.<WmSensitive>lambdaQuery().eq(WmSensitive::getSensitives,dto.getSensitives()));
        if (count != 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //保存参数
        dto.setCreatedTime(new Date());
        //插入数据库
        boolean result = save(dto);
        if (result){
            //获取Redis中的数据
            String value = cacheService.get(sensitive_key);
            //新增Redis中的数据
            cacheService.set(sensitive_key,value + "," + dto.getSensitives());
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
      return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }


    /**
     * 修改(更新)敏感词
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateWmSensitive(WmSensitive dto) {
        //判断参数
        if (dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询id是否存在
        WmSensitive wmSensitive = getById(dto.getId());
        if (null == wmSensitive){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        boolean result = updateById(dto);
        if (result){
            String value = cacheService.get(sensitive_key);
            String[] values = StringUtils.split(value, ',');

            //敏感词 数组转集合
            List<String> list = new ArrayList<>();
            Collections.addAll(list,values);
            //移除list集合中原来的敏感词
            list.remove(wmSensitive.getSensitives());
          //添加新的敏感词到集合中
            list.add(dto.getSensitives());
            //集合转字符串
            String newValue = StringUtils.join(list, ',');

            //保存更新后的敏感词到Redis中
            cacheService.set(sensitive_key,newValue);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 更新数据库中的数据到Redis 每日
     */
    @PostConstruct //服务启动时优先加载该方法
    @Scheduled(cron = "0 0 4 * * ?")
    public void refreshSesitiveData (){
        //查询所有数据
        List<WmSensitive> list = list();
        //stream流 拿到集合中对象的某个字段，转成新的集合
        List<String> sensitiveList = list.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //集合转字符串逗号拼接
        String value = StringUtils.join(sensitiveList, ',');
        //缓存到Redis中
        cacheService.set(sensitive_key,value);

    }
}
